package com.huang.we_chart.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huang.we_chart.VO.LoginVo;
import com.huang.we_chart.entity.Student;
import com.huang.we_chart.service.StudentService;
import com.huang.we_chart.util.HttpClientResult;
import com.huang.we_chart.util.HttpClientUtil;
import com.huang.we_chart.util.NameLib;
import com.huang.we_chart.util.Result;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;

@RestController
@CrossOrigin
public class LoginTestController {
    @Resource
    private StudentService studentService;

    @PostMapping("/login")
    public  Result  WeChartLogin(@RequestBody LoginVo loginVo){
        HttpClientResult httpClientResult=null;
        String appid="wxc2a3d6a661bad2c5";
        String secret="5d91d1b13ce7dd42c8b327e370c4602a";
        String url="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+loginVo.getJs_code()+"&grant_type=authorization_code";
        Student student = new Student();
        try {
            httpClientResult = HttpClientUtil.doGet(url);
            HttpClientUtil.doGet(url);
            String content = httpClientResult.getContent();

            System.out.println("-----------------------------------------------------");
            System.out.println(loginVo);
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String,String> userInfo = objectMapper.readValue(loginVo.getRawData(), Map.class);
            Map<String,String> contentMap = objectMapper.readValue(content, Map.class);

            student.setDepartmentId(new Random().nextInt(5)+1);
            student.setStudentId("1856064"+String.valueOf(new Random().nextInt(14)+1)+String.valueOf(new Random().nextInt(40)+1));
            student.setStudentName(new NameLib().name());

            student.setAvatarHref(userInfo.get("avatarUrl"));
            student.setNickName(userInfo.get("nickName"));
            student.setOpenid(contentMap.get("openid"));
            System.out.println(student);

            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.eq("openid",student.getOpenid());
            boolean save = studentService.saveOrUpdate(student,studentQueryWrapper);

        } catch (Exception e) {
            e.printStackTrace();
        }
          student.setOpenid(null);
        return new Result("200","success",student);

    }
}
